from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from django.db import transaction
from django.utils import timezone
from datetime import datetime, timedelta
from decimal import Decimal
from .models import DriverAccount, TransactionRecord
from login.models import User
import logging

logger = logging.getLogger(__name__)

class DriverBalanceView(APIView):
    """司机余额查询接口"""
    
    def get(self, request):
        driver_id = request.GET.get('driver_id')
        logger.info(f"查询余额请求 - driver_id: {driver_id}, 所有参数: {request.GET}")

        if not driver_id:
            logger.error("缺少driver_id参数")
            return Response({"error": "缺少driver_id参数"}, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 首先获取用户对象
            from login.models import User
            try:
                user = User.objects.get(id=driver_id)
                logger.info(f"查询余额 - 找到用户: {user.id} - {user.real_name}")
            except User.DoesNotExist:
                logger.error(f"查询余额 - 用户不存在: {driver_id}")
                return Response({"error": "用户不存在"}, status=status.HTTP_400_BAD_REQUEST)

            # 获取或创建司机账户
            driver_account, created = DriverAccount.objects.get_or_create(
                driver_id=user,  # 传递用户对象而不是ID
                defaults={
                    'balance': Decimal('0.00'),
                    'frozen_amount': Decimal('0.00'),
                    'status': 1  # 正常状态
                }
            )

            if created:
                logger.info(f"为用户 {driver_id} 创建了新的司机账户")

            return Response({
                "driver_id": driver_id,
                "balance": float(driver_account.balance),
                "frozen_amount": float(driver_account.frozen_amount),
                "available_balance": float(driver_account.balance - driver_account.frozen_amount),
                "status": driver_account.status,
                "updated_at": driver_account.updated_at
            })
        except Exception as e:
            logger.error(f"查询司机余额失败: {str(e)}")
            return Response({"error": "查询余额失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class IncreaseBalanceView(APIView):
    """增加司机余额接口"""
    
    def post(self, request):
        driver_id = request.data.get('driver_id')
        amount = request.data.get('amount')
        remark = request.data.get('remark', '余额充值')

        logger.info(f"充值请求 - driver_id: {driver_id}, amount: {amount}, remark: {remark}")
        logger.info(f"请求数据: {request.data}")

        if not driver_id or amount is None:
            logger.error(f"缺少必要参数 - driver_id: {driver_id}, amount: {amount}")
            return Response({"error": "缺少必要参数"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            amount = Decimal(str(amount))
            if amount <= 0:
                return Response({"error": "金额必须大于0"}, status=status.HTTP_400_BAD_REQUEST)
        except Exception:
            return Response({"error": "金额格式错误"}, status=status.HTTP_400_BAD_REQUEST)
        
        # 使用PaymentService处理余额增加
        from .services import PaymentService
        success, result = PaymentService.add_driver_balance(driver_id, amount, remark)

        if success:
            return Response({
                "message": "余额增加成功",
                "driver_id": driver_id,
                "old_balance": result["old_balance"],
                "new_balance": result["new_balance"],
                "increased_amount": result["added_amount"],
                "transaction_id": result["transaction_id"]
            })
        else:
            logger.error(f"增加余额失败: {result}")
            return Response({"error": result}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class DecreaseBalanceView(APIView):
    """减少司机余额接口"""
    
    def post(self, request):
        driver_id = request.data.get('driver_id')
        amount = request.data.get('amount')
        remark = request.data.get('remark', '余额扣减')
        
        if not driver_id or amount is None:
            return Response({"error": "缺少必要参数"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            amount = Decimal(str(amount))
            if amount <= 0:
                return Response({"error": "金额必须大于0"}, status=status.HTTP_400_BAD_REQUEST)
        except Exception:
            return Response({"error": "金额格式错误"}, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            with transaction.atomic():
                # 首先获取用户对象
                from login.models import User
                try:
                    user = User.objects.get(id=driver_id)
                except User.DoesNotExist:
                    return Response({"error": "用户不存在"}, status=status.HTTP_400_BAD_REQUEST)

                # 获取司机账户
                try:
                    driver_account = DriverAccount.objects.get(driver_id=user)
                except DriverAccount.DoesNotExist:
                    return Response({"error": "司机账户不存在"}, status=status.HTTP_404_NOT_FOUND)

                # 检查余额是否足够
                available_balance = driver_account.balance - driver_account.frozen_amount
                if available_balance < amount:
                    return Response({
                        "error": "余额不足",
                        "available_balance": float(available_balance),
                        "requested_amount": float(amount)
                    }, status=status.HTTP_400_BAD_REQUEST)
                
                # 更新余额
                old_balance = driver_account.balance
                driver_account.balance -= amount
                driver_account.save()
                
                # 创建交易记录
                transaction_record = TransactionRecord.objects.create(
                    driver_id=user,  # 使用用户对象
                    transaction_type=1,  # 支出
                    amount=amount,
                    balance=driver_account.balance,
                    transaction_time=timezone.now(),
                    remark=remark
                )
                
                return Response({
                    "message": "余额扣减成功",
                    "driver_id": driver_id,
                    "old_balance": float(old_balance),
                    "new_balance": float(driver_account.balance),
                    "decreased_amount": float(amount),
                    "transaction_id": transaction_record.id
                })

        except Exception as e:
            logger.error(f"减少余额失败: {str(e)}")
            return Response({"error": "操作失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class DriverTransactionHistoryView(APIView):
    """司机交易记录查询接口"""
    
    def get(self, request):
        driver_id = request.GET.get('driver_id')
        date_type = request.GET.get('date_type', 'all')  # all, daily, monthly
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        page = int(request.GET.get('page', 1))
        page_size = int(request.GET.get('page_size', 20))
        
        if not driver_id:
            return Response({"error": "缺少driver_id参数"}, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 首先获取用户对象
            from login.models import User
            try:
                user = User.objects.get(id=driver_id)
            except User.DoesNotExist:
                return Response({"error": "用户不存在"}, status=status.HTTP_400_BAD_REQUEST)

            # 基础查询
            queryset = TransactionRecord.objects.filter(driver_id=user).order_by('-transaction_time')
            
            # 日期过滤
            if date_type == 'daily':
                # 按日查询
                if start_date:
                    start = datetime.strptime(start_date, '%Y-%m-%d')
                    queryset = queryset.filter(transaction_time__gte=start)
                if end_date:
                    end = datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1)
                    queryset = queryset.filter(transaction_time__lt=end)
                else:
                    # 默认查询今天
                    today = timezone.now().date()
                    queryset = queryset.filter(
                        transaction_time__gte=today,
                        transaction_time__lt=today + timedelta(days=1)
                    )
            
            elif date_type == 'monthly':
                # 按月查询
                if start_date:
                    start = datetime.strptime(start_date, '%Y-%m')
                    queryset = queryset.filter(transaction_time__gte=start)
                if end_date:
                    end = datetime.strptime(end_date, '%Y-%m')
                    next_month = end.replace(day=28) + timedelta(days=4)
                    end = next_month.replace(day=1)
                    queryset = queryset.filter(transaction_time__lt=end)
                else:
                    # 默认查询本月
                    now = timezone.now()
                    first_day = now.replace(day=1)
                    queryset = queryset.filter(transaction_time__gte=first_day)
            
            # 分页
            total = queryset.count()
            start_idx = (page - 1) * page_size
            end_idx = start_idx + page_size
            transactions = queryset[start_idx:end_idx]
            
            # 序列化数据
            transaction_list = []
            for trans in transactions:
                transaction_list.append({
                    "id": trans.id,
                    "transaction_type": trans.transaction_type,
                    "transaction_type_name": trans.get_transaction_type_display(),
                    "amount": float(trans.amount),
                    "balance": float(trans.balance),
                    "transaction_time": trans.transaction_time,
                    "remark": trans.remark,
                    "order_id": trans.order_id
                })
            
            # 统计信息
            from django.db.models import Sum
            total_income = queryset.filter(transaction_type=0).aggregate(
                total=Sum('amount'))['total'] or Decimal('0')
            total_expense = queryset.filter(transaction_type=1).aggregate(
                total=Sum('amount'))['total'] or Decimal('0')
            
            return Response({
                "driver_id": driver_id,
                "date_type": date_type,
                "total": total,
                "page": page,
                "page_size": page_size,
                "total_pages": (total + page_size - 1) // page_size,
                "transactions": transaction_list,
                "statistics": {
                    "total_income": float(total_income),
                    "total_expense": float(total_expense),
                    "net_amount": float(total_income - total_expense)
                }
            })
            
        except ValueError as e:
            return Response({"error": "日期格式错误"}, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            logger.error(f"查询交易记录失败: {str(e)}")
            return Response({"error": "查询失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)



# 在文件末尾添加

class DriverIncomeAnalysisView(APIView):
    """司机收入分析Agent接口"""
    
    def get(self, request):
        driver_id = request.GET.get('driver_id')
        start_date = request.GET.get('start_date')
        end_date = request.GET.get('end_date')
        
        logger.info(f"收入分析请求参数: driver_id={driver_id}, start_date={start_date}, end_date={end_date}")
        
        if not all([driver_id, start_date, end_date]):
            return Response({
                "code": 400,
                "message": "缺少必要参数：driver_id, start_date, end_date",
                "data": None
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 验证日期格式
            datetime.strptime(start_date, '%Y-%m-%d')
            datetime.strptime(end_date, '%Y-%m-%d')
            
            # 使用收入分析器
            from .income_analyzer import DriverIncomeAnalyzer
            analyzer = DriverIncomeAnalyzer()
            result = analyzer.analyze_driver_income(driver_id, start_date, end_date)
            
            if "error" in result:
                return Response({
                    "code": 400,
                    "message": result["error"],
                    "data": None
                }, status=status.HTTP_400_BAD_REQUEST)
            
            return Response({
                "code": 200,
                "message": "收入分析成功",
                "data": result
            })
            
        except ValueError as e:
            return Response({
                "code": 400,
                "message": "日期格式错误，请使用YYYY-MM-DD格式",
                "data": None
            }, status=status.HTTP_400_BAD_REQUEST)
        except Exception as e:
            logger.error(f"收入分析失败: {str(e)}")
            return Response({
                "code": 500,
                "message": "收入分析失败",
                "data": None
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class DriverIncomeReportView(APIView):
    """司机收入报告推送接口"""
    
    def post(self, request):
        driver_id = request.data.get('driver_id')
        analysis_result = request.data.get('analysis_result')
        
        if not all([driver_id, analysis_result]):
            return Response({
                "error": "缺少必要参数"
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 这里可以集成推送服务，如短信、站内信、APP推送等
            # 目前返回模拟推送结果
            
            push_result = {
                "driver_id": driver_id,
                "push_time": timezone.now(),
                "push_channels": ["app_push", "sms"],
                "analysis_summary": analysis_result.get("analysis", {}).get("analysis_summary", ""),
                "status": "success"
            }
            
            return Response({
                "message": "收入报告推送成功",
                "push_result": push_result
            })
            
        except Exception as e:
            logger.error(f"报告推送失败: {str(e)}")
            return Response({
                "error": "报告推送失败"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
